package com.eboss2.sbs.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.TabBasicActivity;
import com.eboss2.sbs.adapter.AdapterTrans;
import com.eboss2.sbs.adapter.FootviewAdapter;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.consts.Constant;
import com.eboss2.sbs.database.dao.TransDataDao;
import com.eboss2.sbs.http.HttpUtil;
import com.eboss2.sbs.model.FirstData;
import com.eboss2.sbs.model.FirstPageData;
import com.eboss2.sbs.model.FirstPicData;
import com.eboss2.sbs.model.MySbsInfo;
import com.eboss2.sbs.model.TransDataBean;
import com.eboss2.sbs.model.TransInfo;
import com.eboss2.sbs.myapplication.MyApplication;
import com.eboss2.sbs.util.RxBus;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.hxchat.utils.APPConfig;
import com.hxchat.utils.SharedPreferencesUtils;
import com.loopj.android.http.RequestParams;
import com.mytools.tool.activityManager.MyActivityManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tool.utils.utils.StringUtils;
import com.tool.utils.utils.ToastUtils;
import com.tool.utils.utils.UtilPreference;
import com.tool.utils.view.MyGridView;
import com.tool.utils.view.MyListView;
import com.tool.utils.view.RTextView;
import com.tool.utils.view.RoundImageView;
import com.tool.utils.view.ZzHorizontalProgressBar;
import com.views.ratingstar.RatingStarView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

public class FirstActivity extends TabBasicActivity {
    public static final String TAG = "FirstActivity";
    @BindView(R.id.gridView)
    MyGridView gridView;
    @BindView(R.id.scroolView)
    PullToRefreshScrollView scroolView;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.tv_ratingstar)
    RatingStarView tvRatingstar;
    @BindView(R.id.tv_conmment)
    TextView tvConmment;
    @BindView(R.id.id_progressbar5)
    ZzHorizontalProgressBar idProgressbar5;
    @BindView(R.id.tv_sorce5)
    TextView tvSorce5;
    @BindView(R.id.id_progressbar4)
    ZzHorizontalProgressBar idProgressbar4;
    @BindView(R.id.tv_sorce4)
    TextView tvSorce4;
    @BindView(R.id.id_progressbar3)
    ZzHorizontalProgressBar idProgressbar3;
    @BindView(R.id.tv_sorce3)
    TextView tvSorce3;
    @BindView(R.id.id_progressbar2)
    ZzHorizontalProgressBar idProgressbar2;
    @BindView(R.id.tv_sorce2)
    TextView tvSorce2;
    @BindView(R.id.id_progressbar1)
    ZzHorizontalProgressBar idProgressbar1;
    @BindView(R.id.tv_sorce1)
    TextView tvSorce1;
    @BindView(R.id.listview)
    MyListView listview;
    @BindView(R.id.iv_img_header)
    RoundImageView ivImgHeader;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_time0)
    TextView tvTime0;
    @BindView(R.id.ll_user_info)
    LinearLayout llUserInfo;
    @BindView(R.id.tv_total_amt)
    TextView tvTotalAmt;
    @BindView(R.id.tv_coupon_num)
    TextView tvCouponNum;
    @BindView(R.id.tv_change_time)
    TextView tvChangeTime;
    @BindView(R.id.tv_change)
    RTextView tvChange;
    @BindView(R.id.tv_change_time1)
    TextView tvChangeTime1;
    @BindView(R.id.tv_change1)
    RTextView tvChange1;

    private long groupId;
    private long userId;

    private boolean changeTime = false;
    private boolean changeTime1 = false;

    private int time_type = 1;
    private int data_time_type = 1;

    private boolean isShow = false;

    private ArrayList<FirstData> firstData = new ArrayList<FirstData>();
    private FootviewAdapter mFootviewAdapter;

    private FirstPageData firstPageData;

    private TransDataDao dao = new TransDataDao();
    private AdapterTrans adapterTrans;
    private List<TransInfo> list = new ArrayList<TransInfo>() {
    };
    private Observable<Boolean> observable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_first);
        ButterKnife.bind(this);
        MyActivityManager.getInstance().addActivity(this);
        initView();
        reload();
    }

    @SuppressWarnings("deprecation")
    private void initView() {
        showView(R.id.titleback_btn_back, false);
        setTvText(R.id.tv_title, "首页");

        scroolView.setMode(PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);
        scroolView.setOnRefreshListener(new PullToRefreshViewEvent()); //下拉刷新 上拉加载

        adapterTrans = new AdapterTrans(mContext, list);
        gridView.setAdapter(adapterTrans);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (list.size() - 1 == i) {
                    startActivity(new Intent(mContext, TransChannelActivity.class));
                }
            }
        });

        //注册事件
        observable = RxBus.getInstance().register(FirstActivity.TAG);
        observable.subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    initData();
                }
            }
        });


        listview.setEnabled(false);
        mFootviewAdapter = new FootviewAdapter(this, listview);
        listview.setAdapter(mFootviewAdapter);
        listview.setFooterDividersEnabled(false);
        mFootviewAdapter.setAdapterData(firstData);

        tvChangeTime.setText(StringUtils.getCurrentDate("yyyy-MM-dd"));
        tvChange.setText("按月统计");

        tvChangeTime1.setText(StringUtils.getCurrentDate("yyyy-MM-dd"));
        tvChange1.setText("按月统计");


    }

    private void initData() {

        list.clear();
        //首次从数据库里加载类型
        List<TransDataBean> transDataBeans = dao.query(Constant.NEWS_CHANNEL_ENABLE);
        if (transDataBeans.size() == 0) {
            //初始化添加
            dao.addInitData(firstPageData.getShopDataList());
            transDataBeans = dao.query(Constant.NEWS_CHANNEL_ENABLE);
        }

        //循环解析
        for (TransDataBean dataBean : transDataBeans) {
            TransInfo info = new TransInfo();
            info.setName(dataBean.getChannelName());
            info.setValue(dataBean.getValue());
            info.setType(dataBean.getType());
            list.add(info);
        }

        //添加最后一个按钮
        TransInfo info = new TransInfo();
        info.setValue("更多");
        list.add(info);
        adapterTrans.notifyDataSetChanged();




    }


    private FirstData getFirstData(String name, String pay_rate, String recevice_money, String recevice_count, String refund_money, String refund_count, int color) {
        FirstData firstData = new FirstData();
        firstData.setPay_name(name);
        firstData.setPay_rate(Float.parseFloat(pay_rate));
        firstData.setRecevice_money(recevice_money);
        firstData.setRecevice_count(recevice_count);
        firstData.setRefund_money(refund_money);
        firstData.setRefund_count(refund_count);
        firstData.setColor(color);
        return firstData;
    }

    private boolean getDbData() {
        List<TransDataBean> transDataBeans = dao.queryAll();
        if (transDataBeans.size() == 0) {
            return false;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        getShopInfo();
        getDataInfo();
    }

    private void getDataInfo() {
        if (!isShow) {
            showProgress("加载中...");
        }
        RequestParams params = new RequestParams();
        params.add("shopId", MyApplication.getmInstance().getLoginMEntity().getShopid() + "");
        params.put("type", data_time_type);
        HttpUtil.get(Config.SBS_INDEX_2, params, new HttpUtil.RequestListener() {
            @Override
            public void success(String response) {
                if (!isShow){
                    disShowProgress();
                }

                try {
                    JSONObject result = new JSONObject(response);

                    if (!result.optBoolean("status")) {
                        ToastUtils.CustomShow(mContext, result.optString("message"));
                    } else {

                        Gson gson = new Gson();
                        FirstPicData firstPicData = gson.fromJson(result.optString("data"), new TypeToken<FirstPicData>() {
                        }.getType());
                        if (firstPicData != null) {


                            firstData.clear();
                            firstData.add(getFirstData("支付宝",  firstPicData.getAliPercent(), firstPicData.getAliAmount()+"", firstPicData.getAliCount()+"",
                                    firstPicData.getAliRefundAmount()+"", firstPicData.getAliRefundCount()+"", Color.parseColor("#00a0e9")));

                            firstData.add(getFirstData("微信", firstPicData.getWxPercent(), firstPicData.getWxAmount()+"", firstPicData.getWxCount()+"",
                                    firstPicData.getWxRefundAmount()+"", firstPicData.getWxRefundCount()+"", Color.parseColor("#3cb034")));

                            firstData.add(getFirstData("钱包", firstPicData.getWalletPercent(), firstPicData.getWalletAmount()+"", firstPicData.getWalletCount()+"",
                                    firstPicData.getWalletRefundAmount()+"", firstPicData.getWalletRefundCount()+"", Color.parseColor("#ff2400")));

                            firstData.add(getFirstData("刷卡", firstPicData.getCardPercent(), firstPicData.getCardAmount()+"", firstPicData.getCardCount()+"",
                                    firstPicData.getCardRefundAmount()+"", firstPicData.getCardRefundCount()+"", Color.parseColor("#ff8f2b")));

                            firstData.add(getFirstData("现金", firstPicData.getCashPercent(), firstPicData.getCashAmount()+"", firstPicData.getCashCount()+"",
                                    firstPicData.getCashRefundAmount()+"", firstPicData.getCashRefundCount()+"", Color.parseColor("#6c00ff")));
                            mFootviewAdapter.setAdapterData(firstData);
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "doLogin() Exception: " + e.getMessage());
                }
            }

            @Override
            public void failed(Throwable error) {
                if (!isShow) {
                    disShowProgress();
                }
                showE404();
            }
        });
    }

    private void getShopInfo() {
        if (!isShow) {
            showProgress("加载中...");
        }

        String url = Config.SBS_MY_INFO;
        RequestParams params = new RequestParams();
        params.put("shopId", MyApplication.getmInstance().getLoginMEntity().getShopid() + "");


        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void success(String response) {
                if (!isShow) {
                    disShowProgress();
                }
                try {
                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        return;
                    }
                    MySbsInfo sbsInfo = new Gson().fromJson(result.optString("data"), new TypeToken<MySbsInfo>() {
                    }.getType());
                    if (sbsInfo != null) {
                        ImageLoader.getInstance().displayImage(sbsInfo.getIcon(), ivImgHeader);

//                        UtilPreference.saveString(mContext, "head_img", sbsInfo.getIcon());
//                        SharedPreferencesUtils.setParam(mContext,APPConfig.USER_NAME,UtilPreference.getStringValue(mContext, "username"));
                        SharedPreferencesUtils.setParam(mContext,APPConfig.USER_NAME,sbsInfo.getShopName());
                        SharedPreferencesUtils.setParam(mContext, APPConfig.USER_HEAD_IMG,sbsInfo.getIcon());
                        tvName.setText(sbsInfo.getShopName());
                        tvTime0.setText("开店时间：" + sbsInfo.getGmtCreate());
                        groupId = sbsInfo.getGroupId();
                        userId = sbsInfo.getUserId();
                    }
                } catch (Exception e) {
                    e.getMessage();
                }
            }

            @Override
            public void failed(Throwable error) {
                if (!isShow) {
                    disShowProgress();
                }
                showE404();
            }
        });
    }

    private void reload() {
        list.clear();
        getdata();
    }

    private void getdata() {

        isShow = true;
        showProgress("加载中...");

        RequestParams params = new RequestParams();
        params.add("shopId", MyApplication.getmInstance().getLoginMEntity().getShopid() + "");
        params.put("type", time_type);
        HttpUtil.get(Config.SBS_INDEX_1, params, new HttpUtil.RequestListener() {
            @Override
            public void success(String response) {
                scroolView.onRefreshComplete();
                disShowProgress();
                try {
                    JSONObject result = new JSONObject(response);

                    if (!result.optBoolean("status")) {
                        ToastUtils.CustomShow(mContext, result.optString("message"));
                    } else {

                        Gson gson = new Gson();
                        firstPageData = gson.fromJson(result.optString("data"), new TypeToken<FirstPageData>() {
                        }.getType());
                        if (firstPageData != null) {


                            if (!getDbData()) {
                                initData();
                            } else {
                                dao.updateAll(firstPageData.getShopDataList());
                                initData();
                            }

                            idProgressbar1.setProgress((int) firstPageData.getScoreList().get(0).getOneScore());
                            idProgressbar2.setProgress((int) firstPageData.getScoreList().get(0).getTwoScore());
                            idProgressbar3.setProgress((int) firstPageData.getScoreList().get(0).getThreeScore());
                            idProgressbar4.setProgress((int) firstPageData.getScoreList().get(0).getFourScore());
                            idProgressbar5.setProgress((int) firstPageData.getScoreList().get(0).getFiveScore());

                            tvSorce1.setText(firstPageData.getScoreList().get(0).getOneScore() + "%");
                            tvSorce2.setText(firstPageData.getScoreList().get(0).getTwoScore() + "%");
                            tvSorce3.setText(firstPageData.getScoreList().get(0).getThreeScore() + "%");
                            tvSorce4.setText(firstPageData.getScoreList().get(0).getFourScore() + "%");
                            tvSorce5.setText(firstPageData.getScoreList().get(0).getFiveScore() + "%");

                            tvTotal.setText(firstPageData.getScoreList().get(0).getAvgScore());
                            tvRatingstar.setRating(Float.parseFloat(firstPageData.getScoreList().get(0).getAvgScore()));
                            tvConmment.setText(firstPageData.getScoreList().get(0).getTotalNumber() + "条评价");

                            tvTotalAmt.setText(StringUtils.formatStrMoney(firstPageData.getTradeTotalAmount()+""));
                            tvCouponNum.setText(firstPageData.getTotalVerifyCount()+"");
                        }

                    }

                } catch (Exception e) {
                    Log.e(TAG, "doLogin() Exception: " + e.getMessage());
                }

                isShow = false;
            }

            @Override
            public void failed(Throwable error) {
                isShow = false;
                scroolView.onRefreshComplete();
                disShowProgress();
                showE404();
            }
        });
    }

    @OnClick(R.id.ll_user_info)
    public void onViewClicked() {
        startActivity(new Intent(mContext, MyInfoActivity.class).putExtra("groupId", groupId).putExtra("userId", userId));
    }

    @OnClick({R.id.tv_change, R.id.tv_change1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_change:
                changeTime = !changeTime;
                tvChange.setText(changeTime ? "按日统计" : "按月统计");
                tvChangeTime.setText(changeTime ? StringUtils.getCurrentDate("yyyy-MM") : StringUtils.getCurrentDate("yyyy-MM-dd"));
                time_type = changeTime ? 2 : 1;
                reload();
                break;
            case R.id.tv_change1:
                changeTime1 = !changeTime1;
                tvChange1.setText(changeTime1 ? "按日统计" : "按月统计");
                tvChangeTime1.setText(changeTime1 ? StringUtils.getCurrentDate("yyyy-MM") : StringUtils.getCurrentDate("yyyy-MM-dd"));
                data_time_type = changeTime1 ? 2 : 1;
                getDataInfo();
                break;
        }
    }

    //下拉刷新 上拉加载
    public class PullToRefreshViewEvent implements PullToRefreshBase.OnRefreshListener<ScrollView> {
        @Override
        public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
            reload();
            getDataInfo();
        }
    }




}
